import os
import time
import json
import urllib3
from datetime import datetime
from flask import jsonify
from basic.config import GlobalInfo, GlobalCfg
from basic.spider import Spider
from basic.messager import XiaoLB
from modules.module import WebsiteModule
from modules.sigalarm.utils import EventType, Event, EventQueue, Messager, NetSpider
from modules.sigalarm.sig import Sig

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


class Sigalarm(WebsiteModule):

    def __init__(self, parent):
        super(Sigalarm, self).__init__(parent, 'sigalarm',
                                       '议题申报提醒服务，自动检测议题记事本，发生变动时提醒相关组织人员。')
        self.independent = True
        self.admin = ''
        self.sigs = []

        self.add_routes('sigalarm_state_cards', '/sigalarm_state_cards', self.get_check_state, ['GET'])
        self.add_routes('sigalarm_logs', '/sigalarm_logs', self.get_logs, ['GET'])

        if not self.enable():
            return

        with open(GlobalCfg.sigalarm_cfg, 'r') as f:
            config = json.load(f)

            NetSpider.init(Spider(config['spider_proxies']))
            Messager.init(XiaoLB(config['xiaolb_server'], config['xiaolb_auth']))
            self.admin = config['admin']
            self.sigs = [Sig(config['name'], config['etherpad'], config['contacts'], config['contacts_group'], self.workspace.path)
                         for config in config['sigmap']]

    def run(self):
        self.setproctitle("[devkit service process] - sigalarm")
        while True:
            if not self.enable():
                return

            for sig in self.sigs:
                self.runlog.log(f'开始检测{sig.name}。')

                sig.begin()
                sig.detect_meeting()
                sig.detect_etherpad()
                sig.end()

                time.sleep(5)  # in case server busy.

            # 处理消息
            self._process_events()
            time.sleep(30)

    def _process_events(self):
        events = EventQueue.getall()
        for event in events:
            sig_name = event.sig.name
            etherpad = event.sig.etherpad
            contacts = event.sig.contacts
            contacts_group = event.sig.contacts_group
            if event.event_type == EventType.SIG_FIRST_INIT:
                self.runlog.log(f'[{sig_name}] 初始化.')
                Messager.send(f'[{sig_name}] 初始化.', contacts, contacts_group)
            elif event.event_type == EventType.ETHERPAD_DOWNLOAD_ERR:
                self.runlog.log(f'[{sig_name}] 议题记事板 内容爬取失败.')
                Messager.send(f'[{sig_name}] 议题记事板 内容爬取失败.', self.admin)
            elif event.event_type == EventType.ETHERPAD_NOTHING_CHANGED:
                self.runlog.log(f'[{sig_name}] 议题记事板 无变动.')
            elif event.event_type == EventType.ETHERPAD_CHANGED:
                self.runlog.log(f'[{sig_name}] 议题记事板 发生变化.')
                msg = f"议题记事板监控(beta) 检测时间: {event.event_time}\n" + \
                      f"SIG: {sig_name}\n" + \
                      f"URL: {etherpad}\n" + \
                      f"DIFF:\n\n{event.content}\n\n\n" + \
                      f"（更多信息： {self.url} ）"
                self.runlog.log(msg)
                Messager.send(msg, contacts, contacts_group)
            elif event.event_type == EventType.MEETING_NEW:
                self.runlog.log(f'[{sig_name}] 检测到新会议: {event.content}.')
                Messager.send(f'[{sig_name}] 检测到新会议: {event.content}.', contacts, contacts_group)
            elif event.event_type == EventType.MEETING_ALARM:
                self.runlog.log(f'[{sig_name}] 会议即将开始: {event.content}')
                Messager.send(f'[{sig_name}] 会议即将开始:\n\t{event.content}\n.', contacts, contacts_group)
            elif event.event_type == EventType.MEETING_NOTHING_CHANGED:
                self.runlog.log(f'[{sig_name}] 会议内容无变化.')
            else:
                assert False

    @staticmethod
    def enable():
        if GlobalCfg.sigalarm_cfg is None or GlobalCfg.sigalarm_cfg == "":
            return False

        if not os.access(GlobalCfg.sigalarm_cfg, os.F_OK):
            return False

        return True

    def homepage(self):
        return self.send_file('sigalarm.html')

    def get_check_state(self):
        sigs = self.sigs
        res = []
        for sig in sigs:
            info = {
                "name": sig.name,
                "url": sig.etherpad,
                "contacts": f"{sig.contacts}, {sig.contacts_group}",
                "content_change_time_last": sig.content_change_time_last,
                "meeting_last": sig.meeting_last,
                "meeting_time_last": sig.meeting_time_last,
            }
            res.append(info)

        return jsonify(res)

    def get_logs(self):
        with open(self.runlog.file, 'r', encoding='utf-8') as f:
            lines = f.readlines()

        return jsonify({'data': '<br>'.join(lines[-1:-500:-1])})


if __name__ == '__main__':
    Sigalarm(None).run()





